function formatTime(time) {
    if (typeof time !== 'number' || time < 0) {
        return time
    }

    var hour = parseInt(time / 3600)
    time = time % 3600
    var minute = parseInt(time / 60)
    time = time % 60
    var second = time

    return ([hour, minute, second]).map(function(n) {
        n = n.toString()
        return n[1] ? n : '0' + n
    }).join(':')
}

function formatSeconds(value) {
    let result = parseInt(value)
    let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
 
    let res = '';
    if(h !== '00') res += `${h}时`;
    if(m !== '00') res += `${m}分`;
    res += `${s}秒`;
    return res;
}

function formatLocation(longitude, latitude) {
    if (typeof longitude === 'string' && typeof latitude === 'string') {
        longitude = parseFloat(longitude)
        latitude = parseFloat(latitude)
    }

    longitude = longitude.toFixed(2)
    latitude = latitude.toFixed(2)

    return {
        longitude: longitude.toString().split('.'),
        latitude: latitude.toString().split('.')
    }
}

function getParamsinfo(url) {
    try {
        var index = url.indexOf('?');
        url = url.match(/\?([^#]+)/)[1];
        var obj = {},
            arr = url.split('&');
        for (var i = 0; i < arr.length; i++) {
            var subArr = arr[i].split('=');
            obj[subArr[0]] = subArr[1];
        }
        return obj;

    } catch (err) {
        return null;
    }
}

function cutStr(str, len) {
    var str_length = 0;
    var str_len = 0;
    var str_cut = new String();
    str_len = str.length;
    for (var i = 0; i < str_len; i++) {
        var a = str.charAt(i);
        str_length++;
        if (escape(a).length > 4) {
            //中文字符的长度经编码之后大于4  
            str_length++;
        }
        str_cut = str_cut.concat(a);
        if (str_length >= len) {
            str_cut = str_cut.concat("...");
            return str_cut;
        }
    }
    //如果给定字符串小于指定长度，则返回源字符串；  
    if (str_length < len) {
        return str;
    }
}

function openWindow(itemobj, _that, callback) {
    console.log(JSON.stringify(itemobj))
        //console.log(typeof(callback))
    let url = ''
    switch (itemobj.operationType) {
        case 'url':
            url = "/pages/web-view/web-view?url=" + encodeURIComponent(itemobj.navigateUrlForWeChat)
            _that.navTo(url, true)
            break;
        case 'product':
            url = '/pages/product/product?id=' + itemobj.targetId
            _that.navTo(url, false)
            break;
        case 'activity':
            url = "/pages/web-view/web-view?url=" + encodeURIComponent(itemobj.navigateUrlForWeChat)
            _that.navTo(url, true)
            break;
        case 'category':
            url = '/pages/shoppingmall/category/category?categoryId=' + itemobj.targetId
            _that.navTo(url, false)
            break;
        case 'coupon':
            url = ''
            break;
        case 'close':
            if (typeof(callback) === 'function') {
                callback('')
            }
            break;
        default:
            if (typeof(callback) === 'function') {
                callback('')
            }
    }
    if (typeof(callback) === 'function') {
        callback('')
    }

}
// 返回false是非空
function isEmpty(value) {
    let backBol = null
    if (!value && typeof value == "object") {
        backBol = true
    } else if (!value && typeof value == "undefined") {
        backBol = true
    } else if (!value && typeof value == 'string') {
        backBol = true
    } else {
        backBol = false
    }
    return backBol
}

function replaceAll(str) {
    if (str != null)
        str = str.replace(new RegExp("\r\n", "gm"), "<br />")
    return str;
}

function remarkUrl(url) {
    let newurl = ''
    let startstr = url.slice(0, url.indexOf('='))
    let endstr = url.slice(url.indexOf('=') + 1)

    if ((url.split('=')).length - 1 > 1) {
        newurl = startstr + "=" + encodeURIComponent(endstr)
    } else {
        newurl = url
    }
    return newurl
}

/**
 * 统一跳转接口,拦截未登录路由
 * navigator标签现在默认没有转场动画，所以用view
 */

function navTo(url, bol, _this) {
    if (bol) {
        if (!_this.hasLogin) {
            url = "/pages/login/login";
            uni.navigateTo({
                url,
            });
            return;
        }
        if (_this.userinfo.authKey == "") {
            url = "/pages/phonenum/phonenum";
            uni.navigateTo({
                url,
            });
            return;
        }
        uni.navigateTo({
            url,
        });
    } else {
        uni.navigateTo({
            url,
        });
    }
}

var dateUtils = {
    UNITS: {
        '年': 31557600000,
        '月': 2629800000,
        '天': 86400000,
        '小时': 3600000,
        '分钟': 60000,
        '秒': 1000
    },
    humanize: function(milliseconds) {
        var humanize = '';
        for (var key in this.UNITS) {
            if (milliseconds >= this.UNITS[key]) {
                humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
                break;
            }
        }
        return humanize || '刚刚';
    },
    format: function(dateStr) {
        var date = this.parse(dateStr)
        var diff = Date.now() - date.getTime();
        if (diff < this.UNITS['天']) {
            return this.humanize(diff);
        }
        var _format = function(number) {
            return (number < 10 ? ('0' + number) : number);
        };
        return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
            _format(date.getHours()) + ':' + _format(date.getMinutes());
    },
    parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
        var a = str.split(/[^0-9]/);
        return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
    }
};

module.exports = {
    formatTime: formatTime,
	formatSeconds: formatSeconds,
    formatLocation: formatLocation,
    dateUtils: dateUtils,
    cutStr: cutStr,
    openWindow: openWindow,
    getParamsinfo: getParamsinfo,
    isEmpty: isEmpty,
    replaceAll: replaceAll,
    remarkUrl: remarkUrl,
    navTo: navTo
}